package cn.tanghom.content.controller.web;

import cn.tanghom.content.model.Accessory;
import cn.tanghom.content.service.AccessoryService;
import cn.tanghom.support.utils.JsonUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file")
public class AccessoryController {

    @Resource
    private AccessoryService accessoryService;

    /**
     * 上传文件
     *
     * @param request
     * @param response 文件流
     * @param request
     * @param response
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String fileupload(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST");
        response.addHeader("Access-Control-Allow-Headers", "content-type");
        String method = request.getMethod();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (method.equals("POST")) {
                Accessory acc = new Accessory();
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile file = multipartRequest.getFile("file");
                Map<String, Object> retMap = accessoryService.upload(acc, file, request);
                if (retMap.size() > 0) {
                    return JsonUtil.toJSONString(retMap);
                } else {
                    map.put("status", "0");
                    return JsonUtil.toJSONString(map);
                }
            }
        } catch (Exception e) {
            map.put("status", "0");
            return JsonUtil.toJSONString(map);
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("/del")
    public String delFile(Long id, HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST,GET");
        response.addHeader("Access-Control-Allow-Headers", "content-type");
        try {
            if (null != id && !"".equals(id)) {
                accessoryService.delete(id,request);
                return true + "";
            }
        } catch (Exception e) {
            return false + "";
        }
        return false + "";
    }

    /**
     * 下载文件
     *
     * @param id 文件Id
     */
    @RequestMapping("/download")
    public void download(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Accessory a = accessoryService.getById(id);
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        String ctxPath = request.getSession().getServletContext().getRealPath("/");
        String downLoadPath = ctxPath + a.getPath();

        long fileLength = new File(downLoadPath).length();

        response.setHeader("Content-disposition", "attachment; filename=" + new String(a.getTitle().getBytes("utf-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));

        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    }

}
